se <- function(x) {sd(x)/sqrt(length(x))}

gov.cohesion <- function(mat) {
    if(nrow(mat)==1) {
        return(0)
    } else {
        return(max(dist(mat)))
    }
}

eff.num.gov.parties <- function(size, gov.seats) {
    shares <- size/gov.seats
    return(1/sum(shares*shares))
}

euclidean.distancer <- function(moving, target1, target2) {
    sqrt(((moving[1]-target1)^2)+((moving[2]-target2)^2))
}
euclidean.distancer <- cmpfun(euclidean.distancer)
 
 

new.gov.represener <- function(vpref, gov1, gov2) {
    gmedian <- l1median(vpref)
    sum2.dist.voter.median.voter <- sum(apply(vpref, 1, euclidean.distancer,
                                          gmedian[1], gmedian[2])^2)
    distance2.to.gov <- apply(vpref, 1, euclidean.distancer, unique(govdim1), unique(govdim2))^2    
}


#for (i in 1:350) { #loop over all parts of combined results
make_ensemble <- function(i) {
 if (file.exists(paste0("mc_newfor/evo/results_combined/ensemble",i,".rds"))==FALSE) {
  print(i)
  files <- paste0("mc_newfor/evo/results/sim_", (((i-1)*100)+1):(i*100), ".rds")
  ensemble <- lapply(files, readRDS)
  ensemble <- rbindlist(ensemble)
  ensemble <- ensemble[,gov.seats:=sum(size[govmember==1]),
                       list(num, experiment, round)]
  ensemble <- ensemble[,c("majority", "A", "HG", "S", "H", "SG"):=list(ifelse(gov.seats>500, 1, 0),
                                                                    ifelse(rule==2,1,0),
                                                                    ifelse(rule==3,1,0),
                                                                    ifelse(rule==4,1,0),
                                                                    ifelse(rule==7,1,0),
                                                                    ifelse(rule==8,1,0))]   
  ensemble <- ensemble[,c("num.gov.parties", "gov.cohesion", "oversized", "eff.num.gov.parties",
                          "Ashare", "HGshare", "Sshare", "Hshare", "SGshare"):=
                       list(sum(govmember),
                            gov.cohesion(cbind(dim1[govmember==1], dim2[govmember==1])),
                            max(ifelse((gov.seats[govmember==1]-size[govmember==1])>500,1,0)),
                            eff.num.gov.parties(size[govmember==1], gov.seats[govmember==1]),
                            mean(A),
                            mean(HG),
                            mean(S),
                            mean(H),
                            mean(SG)
                            ),  list(num, experiment, round)]
 
 #keep only one obs per system for system-level vars
 ensemble <- ensemble[party==1, list(experiment, round, rule, alpha, memory, aspiration,
                                parties, discount, sd.distance, representation,
                                eccentricity, gov.representation,
                                gov.seats, num.gov.parties, gov.cohesion, oversized, majority,
                                eff.num.gov.parties, Ashare, HGshare, Sshare, Hshare, SGshare, ENR, caretaker
                          )] 
 #compute ensemble mean of system-vars
 ensemble <- unique(ensemble[,c("mean.eccentricity", "mean.representation",
                                  "mean.gov.representation",
                                  "se.eccentricity", "se.representation",
                                  "se.gov.representation",
 "mean.gov.seats", "mean.num.gov.parties", "mean.gov.cohesion", "mean.oversized", "mean.majority",
 "se.gov.seats", "se.num.gov.parties", "se.gov.cohesion", "se.oversized", "se.majority",
 "mean.ENgov", "se.ENgov", "mean.Ashare", "mean.HGshare", "mean.Sshare", "mean.Hshare",
 "mean.SGshare", "se.Ashare", "se.HGshare", "se.Sshare", "se.Hshare",  "se.SGshare",
 "mean.ENR", "se.ENR", "mean.caretaker", "se.caretaker") :=
              list(mean(eccentricity),
                   mean(representation),
                   mean(gov.representation),
                    se(eccentricity),
                   se(representation),
                   se(gov.representation),
                   mean(gov.seats),
                   mean(num.gov.parties),
                   mean(gov.cohesion),
                   mean(oversized),
                   mean(majority),
                   se(gov.seats),
                   se(num.gov.parties),
                   se(gov.cohesion),
                   se(oversized),
                   se(majority),
                   mean(eff.num.gov.parties),
                   se(eff.num.gov.parties),
                   mean(Ashare),
                   mean(HGshare),
                   mean(Sshare),
                   mean(Hshare),
                   mean(SGshare),
                   se(Ashare),
                   se(HGshare),
                   se(Sshare),
                   se(Hshare),
                   se(SGshare),
                   mean(ENR),
                   se(ENR),
		   mean(caretaker),
		   se(caretaker)
                   ),
              list(experiment, round)][,list(experiment,
                                                        round,
                                                        alpha,
                                                        memory,
                                                        aspiration,
                                                        parties,
                                                        discount,
                                                        sd.distance,
                                 mean.eccentricity,
                                 mean.representation,
                                 mean.gov.representation,
                                 se.eccentricity,
                                 se.representation,
                                 se.gov.representation,
                                 mean.gov.seats,
                                 mean.num.gov.parties,
                                 mean.gov.cohesion,
                                 mean.oversized,
                                 mean.majority,
                                 se.gov.seats,
                                 se.num.gov.parties,
                                 se.gov.cohesion,
                                 se.oversized,
                                 se.majority,
                                 mean.ENgov,
                                 se.ENgov,
                                 mean.Ashare,
                                 mean.HGshare,
                                 mean.Sshare,
                                 mean.Hshare,
                                 mean.SGshare,
                                 se.Ashare,
                                 se.HGshare,
                                 se.Sshare,
                                 se.Hshare,
                                 se.SGshare,
                                 mean.ENR,
                                 se.ENR,
				 mean.caretaker,
				 se.caretaker)])
 saveRDS(ensemble, file=paste0("mc_newfor/evo/results_combined/ensemble",i,".rds"))
} #file exists
}

